<?php

namespace frontend\controllers;

use common\models\Browse;
use Yii;
use common\models\Website;
use common\models\WebsiteSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\Pagination;
use yii\widgets\LinkPager;

/**
 * WebsiteController implements the CRUD actions for Website model.
 */
class WebsiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Website models.
     * @return mixed
     */
    public function actionIndex3()
    {
        $searchModel = new WebsiteSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionUpdateFaviconUrl()
    {

        $query = new \yii\db\Query();
        $websites = $query->from('website')->all();
        foreach ($websites as $k => $w) {
            $arr = parse_url($w['url']);
            $favicon_url = $arr['scheme'] . '://' . $arr['host'] . '/favicon.ico';
            Website::updateAll(['favicon_url' => $favicon_url], ['id' => $w['id']]);

        }

        exit('更新完毕');
    }

    private function generateCacheKey()
    {
        $controllerId = Yii::$app->controller->id;
        $actionId = Yii::$app->controller->action->id;
        $key = $controllerId . $actionId;
        if (Yii::$app->request->isPost) {
            $params = Yii::$app->request->post();

            if (count($params) > 0) {
                foreach ($params as $p) {
                    $key .= $p;
                }
            }
        }
        return $key;

    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Lists all Website models.
     * @return mixed
     */
    public function actionData()
    {
        $key = $this->generateCacheKey();
        $html = Yii::$app->cache->get($key);
        $pages = null;
        $category_id = Yii::$app->request->post('category_id');
        $title = Yii::$app->request->post('title');
        $page = Yii::$app->request->post('page');
        if ($html === false) {
            $query = new \yii\db\Query();
            $query->from('website w')->innerJoin('category c', 'w.category_id = c.id')
                ->orderBy(['w.page_view' => SORT_DESC])
                ->select(['w.title', 'c.name', 'w.id', 'w.url', 'w.page_view', 'w.favicon_url']);

            if ($category_id > 0) {
                // 查询子类下面的所有数据
                $category_ids = Yii::$app->db->createCommand('call sp_showChildLst("' . $category_id . '")')->queryAll();

                $ids = array();
                foreach ($category_ids as $cate) {
                    array_push($ids, $cate['id']);
                }

                $query->andWhere(['in', 'category_id', $ids]);
            }

            if (isset($title) && $title != '') {
                $query->andWhere(['or', ['like', 'title', $title], ['like', 'url', $title]]);
            }
            $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => '42', 'page' => $page]);
            Yii::$app->cache->set($key . 'pages', $pages, 10);
            $data = $query//->orderBy(['page_view' => SORT_DESC])
            ->offset($pages->offset)
                ->limit($pages->limit)
                ->all();
            Yii::$app->cache->set($key, $data, 10);

            $html = null;
            if (isset($data) && count($data) > 0) {

                foreach ($data as $d) {

                    $html .= '<a class="website_url" data-id="' . $d['id'] . '"  target="_blank" title="' . $d['title'] . '" href="' . $d['url'] . '" >';
                    $html .= '	<div class="col-md-2 col-sm-4 col-xs-12">';
                    $html .= '	    <div class="info-box">';
                    $html .= '	        <span class="info-box-icon" style="background-color: white;">';
                    $html .= '	            <img src="' . $d['favicon_url'] . '" >';
                    $html .= '	        </span>';
                    $html .= '	        <div class="info-box-content">';
                    $html .= '	            <span class="info-box-text">' . mb_substr($d['title'], 0, 20, 'utf-8') . '</span>';
                    $html .= '	            <span class="info-box-number">' . $d['page_view'] . '</span>';
                    $html .= '	        </div>';
                    $html .= '	    </div>';
                    $html .= '	</div>';
                    $html .= '</a>';

                }
                $pages_html = LinkPager::widget(['pagination' => $pages]);
                $html .= $pages_html;
            }
            Yii::$app->cache->set($key, $html, 10);

        }
        exit(json_encode(['data' => $html]));
    }


    /**
     * Displays a single Website model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Jump to url and count page view.
     * @return mixed
     */
    public function actionJump()
    {
        $trans = Yii::$app->db->beginTransaction();
        try {

            $id = Yii::$app->request->post('id');
            $model = $this->findModel($id);
            $model->page_view += 1;
            $model->save();

            $browse = new Browse();
            $browse->website_id = $id;
            $browse->create_at = time();
            $browse->uid = null;

            $browse->save();
            $trans->commit();
            exit(json_encode('success'));
        } catch (\Exception $e) {
            $trans->rollBack();
        }
    }

    /**
     * Creates a new Website model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Website();
        $model->create_at = time();
        $model->url = "http://";
        $model->page_view = 0;
        if ($model->load(Yii::$app->request->post())) {
            $arr = parse_url($model->url);
            $model->favicon_url = $arr['scheme'] . '://' . $arr['host'] . '/favicon.ico';
            if ($this->getCountByUrl($model->url) > 0) {
                $model->addError('url', "已经存在");
            } else if ($model->save()) {
                return $this->redirect(['index']);
            }
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Website model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->update_at = time();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Website model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionGetWebsiteInfo()
    {
        $url = Yii::$app->request->post('url');

        $content = file_get_contents($url);
        $cha = mb_detect_encoding($content);
        $content = iconv($cha, "UTF-8", $content);

        $data['title'] = '';
        $data['desc'] = '';
        if (preg_match('/<title>([\s\S]?)<\/title>/i', $content, $matches)) {
            $title = $matches[0];
            $title = str_replace('<title>', '', $title);
            $title = str_replace('</title>', '', $title);
            $data['title'] = $title;
        }

        if (preg_match('/<meta name="description" content=".*" \/>/i', $content, $matches)) {
            $desc = $matches[0];
            $desc = str_replace('<meta name="description" content="', '', $desc);
            $desc = str_replace('" />', '', $desc);
            $data['desc'] = $desc;
        }

        return json_encode($data);
    }

    /**
     * Finds the Website model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Website the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Website::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function getCountByUrl($url)
    {
        return Website::find()->where(['=', 'url', $url])->count();
    }
}
